using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Reflection;
using OpenComposite.Workflow.Extensions;
using System.Workflow.Runtime;
using System.ServiceModel.Activation;

namespace OpenComposite.Workflow
{
	public class ServiceHostActivation : ServiceHostFactoryBase
	{
		public override ServiceHostBase CreateServiceHost(string constructorString, params Uri[] baseAddresses)
		{
			return Create(constructorString, baseAddresses);
		}

		public static ServiceHost Create(string constructorString, params Uri[] baseAddresses)
		{
			// find the type of the service

			Type serviceType = Type.GetType(constructorString, false);
			if ( serviceType == null ) {
				foreach ( Assembly assembly in AppDomain.CurrentDomain.GetAssemblies() ) {
					serviceType = assembly.GetType(constructorString, false);
					if ( serviceType != null ) {
						break;
					}
				}
			}

			// validate type
			if ( serviceType == null ) {
				throw new ArgumentException("Can't find the assembly to create a service type");
			}
			return Create(serviceType, baseAddresses);
		}

		public static ServiceHost Create(Type serviceType, params Uri[] baseAddresses)
		{
			// create wcf host
			ServiceHost host = new ServiceHost(serviceType, baseAddresses);
			host.Closing += new EventHandler(host_Closing);

			// Service extension for WF Supply Web.Config section with parameters
			WfWcfExtension workflowRuntime = new WfWcfExtension("WorkflowRuntimeConfig");

			// Add the Extension to the ServiceHost collection
			host.Extensions.Add(workflowRuntime);

			return host;

		}

		private static void host_Closing(object sender, EventArgs e)
		{
			WorkflowRuntime wr = ( sender as ServiceHost ).Extensions.Find<WorkflowRuntime>();
			if ( wr != null ) {
				wr.Dispose();
			}
		}
	}
}
